package com.archermind.style.util;

import com.archermind.style.bean.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class SessionUtil {

    private static String devOrProd;

    public static void  setDevOrProd(String devOrProd){
        SessionUtil.devOrProd = devOrProd;
    }

    public static boolean isDev(){
        return "dev".equals(devOrProd);
    }

    public static Integer getCurUserId(){
       User user = getCurUser();
       if(user!=null){
           return user.getId();
       }
       return null;
    }

    public static User getCurUser(){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            return null;
        }
        HttpServletRequest request =attributes.getRequest();
        HttpSession session = request.getSession();

        User user =  (User)session.getAttribute("user");
        String sessionId = session.getId();
        if(user != null && sessionId.equals(session.getServletContext().getAttribute(user.getId().toString())) ){
            return user;
        }
        return null;
        //  user = new User();user.setId(1);   return user;
    }

    public static Set getInstanceIds(User user){
        Set instanceIds = new HashSet();
        if(StringUtils.isNotEmpty(user.getReadInstanceIds())){
            instanceIds.addAll(Arrays.asList(user.getReadInstanceIds().split(",")));
        }
        if(StringUtils.isNotEmpty(user.getWriteInstanceIds())){
            instanceIds.addAll(Arrays.asList(user.getWriteInstanceIds().split(",")));
        }
        return instanceIds;
    }
}
